<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\helper\JwtHelper;
use support\Log;
use ReflectionClass;

class JwtAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {

        // 通过反射获取控制器哪些方法不需要登录
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];


        Log::info('info',['info' => $request->header('Authorization')]);

        // 访问的方法需要登录
        if (!in_array($request->action, $noNeedLogin)) {
            // 拦截请求，返回一个重定向响应，请求停止向洋葱芯穿越
            // 获取请求头中的token
            $token = $request->header('Authorization');
            if (!$token) {
                return json(['code' => 401, 'msg' => '未登录或token已过期']);
            }
        }else{
            return $handler($request);
        }

        // 去掉Bearer前缀
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        try {
            // 验证token
            $payload = JwtHelper::decode($token);
            // 将用户信息注入到请求中
            $request->user = $payload;
            return $handler($request);
        } catch (\Exception $e) {
            return json(['code' => 401, 'msg' => 'token无效或已过期']);
        }
    }
}
